package com.guodi.map.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guodi.core.minio.util.MinioUtil;
import com.guodi.map.entity.MapMyMap;
import com.guodi.map.mapper.MapMyMapMapper;
import com.guodi.map.service.IMapMyMapService;
import com.guodi.map.utils.Base64Util;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @作者: 林楷
 * @日期: 2021/11/18
 * @描述: 我的地图
 */
@Service
public class MapMyMapServiceImpl extends ServiceImpl<MapMyMapMapper, MapMyMap> implements IMapMyMapService {
    @Override
    public boolean add(MapMyMap mapMyMap) throws IOException {
        String url = mapMyMap.getUrl();
        InputStream inputStream;
        // 自定义制图
        if (StringUtils.isBlank(url)) {
            String thumbnail = mapMyMap.getThumbnail();
            if (StringUtils.isBlank(thumbnail)) {
                throw new RuntimeException("thumbnail is null:图片不能为空");
            }
            inputStream = Base64Util.generateImage(thumbnail);

//            MinioUtil.uploadFile(inputStream, "map_my_map", mapMyMap.getName()+"."+mapMyMap.getSuffix());
        } else {
            OkHttpClient httpClient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Response response = httpClient.newCall(request).execute();
            byte[] bytes = response.body().bytes();
            inputStream = new ByteArrayInputStream(bytes);
        }
        String path = MinioUtil.uploadFile(inputStream, "map_my_map", mapMyMap.getName()+"."+mapMyMap.getSuffix());
        mapMyMap.setPath(path);
        return this.save(mapMyMap);
    }
}
